package com.smart.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import com.smart.dto.AttendanceStatus;
import com.smart.mapper.UserMapper;
import com.smart.service.UserService;
import com.smart.util.Pageable;
import com.smart.entity.SysUser;
import javax.annotation.Resource;
import com.smart.vo.SsAttendanceVO;
import cn.hutool.core.util.StrUtil;
import com.smart.util.SysUserUtils;
import com.smart.entity.SsAttendance;
import com.smart.mapper.AttendanceMapper;
import com.smart.service.AttendanceService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smart.service.web.WebInspectionRecordService;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

/**
 * @author lgb
 * @date 2020年6月10日 下午7:38:28
 * Copyright (C) 深圳工勘科技
 * @说明: 智慧工地serviceImpl
 **/
@Service
public class AttendanceServiceImpl extends BaseServiceImpl<SsAttendance,
		Long> implements AttendanceService {

	@Resource
	private AttendanceMapper aMapper;
	@Resource
	private UserMapper userMapper;

	@Resource
	private UserService userService;
	@Resource
	private WebInspectionRecordService webInspectionRecordService;
	
	/**
	 * @param pageable
	 * @see :分页查询数据
	 **/
	@Override
	@Transactional(readOnly=true)
	public com.smart.util.Page<SsAttendance> findPage(Pageable pageable) {
		List<SsAttendance> list = new ArrayList<>();
		String name = pageable.getSearch().get("name");
		String identity = pageable.getSearch().get("identity");
		String startTime = pageable.getSearch().get("createDate_begin");
		String endTime = pageable.getSearch().get("createDate_end");
		int total = aMapper.findAttendanceTotal(name,identity,startTime,endTime);
		if(total == 0){
			return new com.smart.util.Page<SsAttendance>(list,pageable,Long.valueOf(total));
		}
		int start = (pageable.getPage()-1) * pageable.getLimit();
		int end = pageable.getPage() * pageable.getLimit();
		list = aMapper.findAttendanceList(name,identity,startTime,endTime,start,end);
		return new com.smart.util.Page<SsAttendance>(list,pageable,Long.valueOf(total));
	}

	/** 
	 * (non-Javadoc)
	 * @see: 
	 **/
	@Override
	@Transactional(readOnly=true)
	public SsAttendanceVO getLatestSsAttendance() {
		SysUser user = SysUserUtils.getSysUser();
		return aMapper.getLatestSsAttendance(user.getId());
	}

	/** 
	 * (non-Javadoc)
	 * @see: 查询页面
	 **/
	@Override
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true)
	public List<SsAttendance> findPage(String createTime,Integer pageNum, 
			Integer pageSize) {
		Long id = SysUserUtils.getSysUser().getId();
        LambdaQueryWrapper<SsAttendance> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(SsAttendance::getUserId,id);
        if (StrUtil.isNotEmpty(createTime)) {
            wrapper.gt(SsAttendance::getCreateTime,createTime+" 00:00:00");
            wrapper.le(SsAttendance::getCreateTime,createTime+" 23:59:59");
        }
        wrapper.orderByDesc(SsAttendance::getCreateTime);
        IPage<SsAttendance> i=page(new Page<SsAttendance>(pageNum,pageSize),wrapper);
        return i.getRecords();
	}



	/**
	 * @param type 1:当日2:当周3:当月
	 * @return 作业进度统计
	 **/
	@Override
	@Transactional(readOnly=true)
	public Integer[] statisticalSsWork(int type) {
		//获取普通员工数
		List<SysUser> users= userMapper.findUserByAttendance();
		//获取对应时间段打卡人员
		List<SsAttendance> list= aMapper.findAttendanceByDate(type);
		Integer[] res= {list.size(),0};//打卡次数、未打卡次数
		Calendar calendar = Calendar.getInstance();
		Date today = new Date();
		calendar.setTime(today);// 此处可换为具体某一时间
		int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
		int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
		if (weekDay == 1) {
			weekDay = 7;
		} else {
			weekDay = weekDay - 1;
		}
		switch (type){
			case 1:res[1]=users.size()-list.size();;break;
			case 2:
				res[1]=users.size()*weekDay-list.size();;break;
			case 3:
				res[1]=users.size()*monthDay-list.size();break;
		}
		return res;
	}

	@Override
	public List<AttendanceStatus> findAttenByUser(int user_id, String date) {

		try{
		List<SysUser> users=userMapper.findUserByAttendance();
		List<SsAttendance> attendances=aMapper.findAttendByMonth(date);//3:月份
		List<AttendanceStatus> attendanceStatusList=new ArrayList<>();
		users.forEach(x->{//遍历打卡人员
			attendances.forEach(y->{//遍历考勤记录
				if(x.getId().intValue()==y.getUserId()){//同一人
					AttendanceStatus attendanceStatus=new AttendanceStatus();
					attendanceStatus.setDate(y.getCreateDate());
					attendanceStatus.setTotal(1);
					attendanceStatusList.add(attendanceStatus);
				}
			});
		});
		//获取指定月份所有时间
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
		Date d=sf.parse(date);
		Calendar cld=Calendar.getInstance();
		cld.setTime(d);
		//判断传入时间是否在本月
		Boolean isThisMonth=isThisMonth(date);
		int monthDay=0;
		if(isThisMonth){
			monthDay = cld.get(Calendar.DAY_OF_MONTH);//获取这个月的已到时间天数
		}else{
			monthDay=getDaysByYearMonth(date);//获取这个月的天数
		}
		//设置为1号
		cld.set(Calendar.DAY_OF_MONTH,1);
		for (int i = 0; i < monthDay; i++, cld.add(Calendar.DATE, 1)) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String df = simpleDateFormat.format(cld.getTime());
			AtomicReference<Boolean> flag= new AtomicReference<>(new Boolean(true));
			attendanceStatusList.forEach(x->{
				if(x.getDate().equals(df)){
					flag.set(false);
				}
			});
			if(flag.get()==true){
				AttendanceStatus attendanceStatus=new AttendanceStatus();
				attendanceStatus.setDate(df);
				attendanceStatus.setTotal(0);
				attendanceStatusList.add(attendanceStatus);
			}
		}
		return attendanceStatusList;
		}catch (Exception e){
		}
		return null;
	}

	/**
	 * 根据年 月 获取对应的月份 天数
	 * */
	public int getDaysByYearMonth(String date) {
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
		Calendar a = Calendar.getInstance();
		//赋值时间
		try {
			a.setTime(sf.parse(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int year=a.get(Calendar.YEAR);
		int month=a.get(Calendar.MONTH);
		a.set(Calendar.YEAR, year);
		a.set(Calendar.MONTH, month);
		a.set(Calendar.DATE, 1);
		a.roll(Calendar.DATE, -1);
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	/**
	 * 判断传入日期是否在本月
	 */
	public boolean isThisMonth(String date){
		//获取传入时间
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
		Calendar cl=Calendar.getInstance();
		//赋值时间
		try {
			cl.setTime(sf.parse(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int inputYearMonthNumber=cl.get(Calendar.YEAR)+cl.get(Calendar.MONTH);
		cl.setTime(new Date());
		int nowYearMonthNumber=cl.get(Calendar.YEAR)+cl.get(Calendar.MONTH);
		if(inputYearMonthNumber==nowYearMonthNumber){
			return true;
		}
		return false;
	}

}